package com.learn.concurrent.itcast.thread.create;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * https://www.trinea.cn/android/java-android-thread-pool/
 */
public class ThreadPool {

    public static void main(String[] args) {
        //newCachedThreadPool
        /*ExecutorService cachedThreadPool= Executors.newCachedThreadPool();
        for(int i=0;i<10;i++){
            final int index=i;
            try {
                Thread.sleep(index* 1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cachedThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread()+" "+index);
                }
            });
        }*/

        //newFixedThreadPool
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int index = i;
            fixedThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread()+" "+index);
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
        }

        /*ScheduledExecutorService scheduledThreadPool =Executors.newScheduledThreadPool(5);
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread()+" 测试");
            }
        },1,3, TimeUnit.SECONDS);*/

        /*ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            singleThreadExecutor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread()+" "+index);
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
        }*/
    }
}
